import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import SearchBar from "../../components/searchbar";
import {
  Button,
  Toast,
  PickerView,
  CascadePickerView,
  Mask,
} from "antd-mobile";
import "./index.scss";
import HouseItem from "../../components/houseItem";
import { getHouseListAPI } from "../../apis/map";
import { baseURL } from "../../utils/request";
import { getCurrentCity } from "../../utils";
import { getAreaAPI } from "../../apis/houselist";
import { getHousesParamsAPI } from "../../apis/profile";

const selectValues = {
  area: null,
  mode: null,
  price: null,
  more: [],
};
const houseBar = [
  { value: "区域", type: "area" },
  { value: "方式", type: "mode" },
  { value: "租金", type: "price" },
  { value: "筛选", type: "more" },
];
const houseMode = [
  { label: "不限", value: null },
  { label: "整租", value: "整租" },
  { label: "合租", value: "合租" },
];
const housePrice = [
  { label: "不限", value: null },
  { label: "1000以下", value: 1000 },
  { label: "2000以下", value: 2000 },
  { label: "3000以下", value: 3000 },
  { label: "4000以下", value: 4000 },
];
export default function HouseList() {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [housesList, setHousesList] = useState([]);
  const [curBar, setCurBar] = useState();
  // 标题高亮状态
  // true 表示高亮； false 表示不高亮
  const [titleSelectedStatus, setTitleSelectedStatus] = useState({
    area: false,
    mode: false,
    price: false,
    more: false,
  });
  const [selectedValues, setSelectedValues] = useState({
    area: null,
    mode: null,
    price: null,
    more: [],
  });
  const [selectedMore, setSelectedMore] = useState({
    floor: [],
    roomType: [],
    supporting: [],
    oriented: [],
  });
  const [options, setOptions] = useState([]);
  const [more, setMore] = useState({});
  const [curCity, setCurCity] = useState(
    JSON.parse(localStorage.getItem("hkzf_city"))
  );
  async function getCurCity() {
    const city = await getCurrentCity();
    setCurCity(city);
    console.log(selectedValues);
    if (selectedValues.city) {
      const { id, rentType, price } = selectValues;
      getHouseList(id, rentType, price);
    } else {
      getHouseList(city.value);
    }
    setBox(city.value);
  }
  async function getHousesParams() {
    const res = await getHousesParamsAPI();
    setSelectedMore(res.body);
  }
  async function setBox(id) {
    let data;
    data = await getArea(id);
    const areaBox = data?.body;
    setOptions(areaBox);
  }
  async function getArea(id) {
    return getAreaAPI(id);
  }
  useEffect(() => {
    getCurCity();
    window.addEventListener("scroll", () => {
      const scrollTopValue =
        document.documentElement.scrollTop / (window.screen.width * 0.01);
      // console.log(scrollTopValue)
      const bar = document.querySelector(".house__search__mid");
      const content = document.querySelector(".house__content");
      if (bar && content) {
        if (scrollTopValue >= 13) {
          bar.style.position = "fixed";
          content.style.paddingTop = "9vw";
        } else {
          bar.style.position = "relative";
          content.style.paddingTop = "0";
        }
      }
    });
    // document.querySelector(".cancelMore").addEventListener('click',()=>{
    //     setMore(more => more={})
    // })
    getHousesParams();
  }, []);
  async function mockApi(key) {
    const children = await getArea(key);
    // console.log(children.body)
    return children.body;
  }
  async function getHouseList(id, rentType, price) {
    let cur;
    try {
      cur = Toast.show({
        icon: "loading",
        content: "加载中…",
        duration: 0,
      });
      console.log(id, rentType, price);
      const res = await getHouseListAPI(id, rentType, price);
      setHousesList(res.body.list);
      cur.close();
    } catch (e) {
      cur.close();
    }
  }
  const clickBar = (cur) => {
    setTimeout(() => {
      setCurBar(cur);
      setVisible(true);
      if (cur !== "more") {
        const box = document.querySelector(".search__choose__box");
        // console.log(box);
        box.style.height = "60vw";
      } else {
        const box = document.querySelector(".more__choose__box");
        // console.log(box);
        box.style.width = "calc(85%)";
      }
    }, 0);
  };
  const cancelBar = () => {
    setVisible(false);
    if (curBar !== "more") {
      const box = document.querySelector(".search__choose__box");
      box.style.height = "0";
    } else {
      const box = document.querySelector(".more__choose__box");
      box.style.width = "0";
    }
  };

  const okBar = () => {
    titleSelectedStatus[curBar] = true;
    setTitleSelectedStatus(titleSelectedStatus);
    // selectedValues[curBar] = selectValues[curBar]
    // console.log(selectedValues);
    let newObj = { ...selectedValues, [curBar]: selectValues[curBar] };
    setSelectedValues(newObj);
    // console.log({...selectedValues,[curBar]:selectValues[curBar]});
    // console.log(selectedValues);
    // setSelectedValues(selectedValues) //bug :标记一下：不用selectedValues不会立即更新（如：{[curBar]:selectedValues[curBar]}
    let { area: cityId, mode: rentType, price, more } = newObj;
    if (rentType) {
      if (rentType === "整租") {
        rentType = true;
      } else {
        rentType = false;
      }
    }
    if (!cityId) {
      cityId = curCity.value;
    }
    getHouseList(cityId, rentType, price);
    cancelBar();
    // console.log(selectedValues)
  };
//   const cancelBarMore = () => {
//     setMore({})
//   }
  const onTagClick = (value, tag) => {
    more[tag] = value;
    setMore({...more});
    // setSelectedValues({ ...selectedValues, more: more });
  };
  // 渲染标签
  function renderFilters(data, tag) {
    
    return data.map((item) => {
      const isSelected = more[tag] === item.value;
      return (
        <span
          key={item.value}
          className={isSelected ? "tagActive" : ""}
          onClick={() => onTagClick(item.value, tag)}
        >
          {item.label}
        </span>
      );
    });
  }
  const bar = () => {
    setMore({})
  }
  return (
    <div className="house__search">
      <Mask visible={visible} onMaskClick={cancelBar} opacity="thin" />
      <div className="house__search__header">
        <i className="iconfont icon-back" onClick={() => navigate(-1)}></i>
        <div className="house__search__content">
          <SearchBar color={"#21b97a"} />
        </div>
      </div>
      <div className="house__search__mid">
        <ul className="house__search__bar">
          {houseBar.map((item, index) => (
            <li
              className={[
                "bar__item",
                titleSelectedStatus[item.type] ? "active__bar" : "",
              ].join(" ")}
              key={item.type}
              onClick={() => clickBar(item.type)}
            >
              <span className="name">{item.value}</span>
              <i className="iconfont icon-arrow"></i>
            </li>
          ))}
        </ul>
        <div className="search__choose__box">
          <div className="search__choose__content">
            {curBar === "area" && (
              <CascadePickerView
                options={options}
                onChange={(val) => {
                  const key = val[0];
                  if (val[1]) {
                    selectValues.area = val[1];
                  }
                  if (!key) return;
                  mockApi(key).then((data) => {
                    setOptions((options) =>
                      options.map((option) => {
                        // console.log(option)
                        if (option.value === key) {
                          return {
                            ...option,
                            children: data.map((x) => {
                              return { label: x.label, value: x.value };
                            }),
                          };
                        }
                        return option;
                      })
                    );
                    // console.log(options)
                  });
                }}
              />
            )}
            {curBar === "mode" && (
              <CascadePickerView
                options={houseMode}
                onChange={(val) => {
                  selectValues.mode = val[0];
                }}
              />
            )}
            {curBar === "price" && (
              <CascadePickerView
                options={housePrice}
                onChange={(val) => {
                  selectValues.price = val[0];
                }}
              />
            )}
          </div>
          <div className="search__choose__btn">
            <Button className="btn cancel" onClick={cancelBar}>
              取消
            </Button>
            <Button className="btn submit" onClick={okBar}>
              确定
            </Button>
          </div>
        </div>

        <div className="more__choose__box">
          <div className="content">
            <dl>
              <dt>户型</dt>
              <dd>{renderFilters(selectedMore.roomType, "roomType")}</dd>
              <dt>朝向</dt>
              <dd>{renderFilters(selectedMore.oriented, "oriented")}</dd>
              <dt>楼层</dt>
              <dd>{renderFilters(selectedMore.floor, "floor")}</dd>
              <dt>房屋配置</dt>
              <dd>{renderFilters(selectedMore.supporting, "supporting")}</dd>
            </dl>
          </div>
          <div className="search__choose__btn">
            <Button className="btn cancelMore" onClick={bar}>
              清除
            </Button>
            <Button className="btn submit" onClick={okBar}>
              确定
            </Button>
          </div>
        </div>
      </div>
      <div className="house__content">
        {housesList.map((item) => (
          <HouseItem
            onClick={() => navigate(`/detail/${item.houseCode}`)}
            key={item.houseCode}
            src={baseURL + item.houseImg}
            title={item.title}
            desc={item.desc}
            tags={item.tags}
            price={item.price}
          />
        ))}
      </div>
    </div>
  );
}
